﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data.OleDb;
using System.Data.SQLite;

namespace SimpleCRM.Units
{
    public class CodeSequnce
    {
        public int CurrentVal { get; set; }
        public DateTime CurrentDate { get; set; }

        public string GetNextCode()
        {
            return DateTimeConvertHelper.GetFormatDate(CurrentDate) + CurrentVal.ToString().PadLeft(5, '0');
        }
    }

    public class CodeHelper
    {

        public static int GetNextID()
        {
            return GetNextID("T_Order");
        }

        public static int GetNextID(string name)
        {
            int maxID = 0;
            string strSql = "SELECT Max(ID) FROM " + name;
            using (IDbConnection cnn = DbHelper.GetConnection())
            {
                maxID = cnn.ExecuteScalar<int>(strSql, null);
            }
            return maxID + 1;
        }

        public static string GetNextCode()
        {
            return GetNextCode(DateTime.Now);
        }

        public static string GetNextCode(DateTime dt)
        {
            CodeSequnce cs = new CodeSequnce();
            cs.CurrentDate = dt;
            cs.CurrentVal = GetDateMaxVal(dt);
            return cs.GetNextCode();
        }

        /// <summary>
        /// 获取某一天的主键记录，如果得到值为零说明还没有添加这一天的记录
        /// 数据库添加过程中，主键记录默认值为1
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private static int GetDateMaxVal(DateTime dt)
        {
            int currentVal = 0;
            string strSql = "SELECT Max(CVAL) FROM T_CODE WHERE CDATA=@CDATA";
            using (IDbConnection cnn = DbHelper.GetConnection())
            {
                currentVal = cnn.ExecuteScalar<int>(strSql, new { CDATA = DateTimeConvertHelper.GetFormatDate(dt) });
            }
            if (currentVal == 0)
            {
                currentVal = 1;
                InsertDateVal(dt);
            }
            return currentVal;
        }


        /// <summary>
        /// 数据库添加过程中，主键记录默认为1
        /// </summary>
        /// <param name="dt"></param>

        private static void InsertDateVal(DateTime dt)
        {
            string strSql = "INSERT INTO T_CODE(CDATA) VALUES(@CDATA)";
            using (IDbConnection cnn = DbHelper.GetConnection())
            {
                cnn.Execute(strSql, new { CDATA = DateTimeConvertHelper.GetFormatDate(dt) });
            }
        }

        public static void UpdateDataVal(DateTime dt)
        {
            string strSql = "UPDATE T_CODE SET CVAL=CVAL+1 WHERE CDATA=@CDATA";
            using (IDbConnection cnn = DbHelper.GetConnection())
            {
                cnn.Execute(strSql, new { CDATA = DateTimeConvertHelper.GetFormatDate(dt) });
            }
        }

    }
}
